using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Framework
{

    public class EditorAssetLoader : AssetLoader
    {
        private float WaitTime;
        public void Initialize(float loadFileTime = 0)
        {
            this.WaitTime = loadFileTime;
            this.waitTime = loadFileTime;
        }
        public EditorAssetLoader()
        {
            this.Enabled = true;
        }
        private Queue<string> _list = new Queue<string>();
        private float waitTime;
        private Dictionary<string, AssetLoadData> _assetsMap = new Dictionary<string, AssetLoadData>();
#if UNITY_EDITOR
        protected override void loadAsset(AssetLoadData value)
        {
            base.loadAsset(value);
            _assetsMap.Add(value.Path, value);
            _list.Enqueue(value.Path);
        }
        protected override void onUpdate(float deltaTime, float unscaledDeltaTime)
        {
            base.onUpdate(deltaTime, unscaledDeltaTime);

            int len = _list.Count;
            while (len-- > 0)
            {
                waitTime -= deltaTime;
                if (waitTime > 0f)
                {
                    return;
                }
                waitTime = this.WaitTime;

                var item = _list.Dequeue();
                if (_assetsMap.TryGetValue(item, out AssetLoadData loadData))
                {
                    if (loadData.RefCount < 1)
                    {
                        return;
                    }
                    if (loadData.IsScene)
                    {
                        LoadSceneParameters parameters = new LoadSceneParameters() { loadSceneMode = LoadSceneMode.Additive, localPhysicsMode = LocalPhysicsMode.None };
                        AsyncOperation asyncOperation = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(loadData.Path, parameters);
                        asyncOperation.allowSceneActivation = false;
                        loadData.Finish(asyncOperation);
                    }
                    else
                    {
                        var asset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(loadData.Path);
                        loadData.Finish(asset);
                    }
                }

            }
        }
        protected override void unloadAsset(string path)
        {
            base.unloadAsset(path);
            if (_assetsMap.TryGetValue(path, out AssetLoadData asset))
            {
                _assetsMap.Remove(path);
                if (asset.IsScene && asset.AsyncOperationScene != null)
                {
                    UnityEditor.SceneManagement.EditorSceneManager.UnloadSceneAsync(asset.Path);
                    unloadScene(path);
                }
            }
        }
#endif

    }

}